package com.hxj.ecokey.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hxj.ecokey.entity.User;
import com.hxj.ecokey.mapper.UserMapper;
import com.hxj.ecokey.service.UserService;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Autowired
    public UserServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    //测试用户
    @PostConstruct
    public void initTestUser() {
        // 先检查用户是否已存在
        User existUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", "test"));
        if (existUser == null) {
            User testUser = new User();
            testUser.setUsername("test");
            testUser.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            testUser.setRegisterTime(new Date());
            userMapper.insert(testUser);
        }
    }
    @Override
    public User register(User user) {
        // 检查用户名是否存在
        User existUser = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (existUser != null) {
            throw new RuntimeException("用户名已存在");
        }

        // 密码加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));

        //设置注册时间
        user.setRegisterTime(new Date());

        // 使用BaseMapper的insert方法
        int result = userMapper.insert(user);
        return result > 0 ? user : null;
    }

    @Override
    public User login(String username, String password) {
        // 根据用户名查询用户
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 验证密码 md5加密
        String encrypted = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!encrypted.equals(user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        return user;
    }
}